#version 2.0
#Knows how to work file and directory(with files)
import hashlib
import os


def get_info_about_out_result():
    out_file = input("Writ result to file? Yes - 1, No  - 0\n")
    try:
     out_file =  int(out_file)
    except ValueError:                                               
     print("What?! Grey? The condition is written for whom?")
    else:                                                           
     get_method(out_file)


def get_method(out_file):
   method = input(f"Please, select method -> {hashlib.algorithms_guaranteed}:\n")
   try:
#next used var method in function get_hash_sum     
      method = hashlib.new(f"{method}")
   except ValueError:
      print("Please select one of the methods presented!")
   else:
      get_path_to_file(method,out_file)
 

def get_path_to_file(method,out_file):
   path = input(f"Please enter the path to the file or folder(directory):\n")
   if os.path.exists(path):
     check_file_or_dir(method,path,out_file)
   else:
      print("Path is incorrect!")


def check_file_or_dir(method,path,out_file):
#Received a file or directory
    if os.path.isdir(path):
       check_empty_dir(method,path,out_file)
    else:
       get_hash_sum(method,read_file(path),out_file)


def check_empty_dir(method,path,out_file):
#the variable concat_into_files_in_bytes contains all the text from allother files
    concat_into_files_in_bytes = b''
#if length list directory == 0 , directory - empty!
    if len( os.listdir(path)  ):
       reader_and_concat_all_files_in_directory_to_one_file(path,concat_into_files_in_bytes)
       get_hash_sum(method,concat_into_files_in_bytes,out_file)
    else:                                                            
       print("Dirrctory is EMPTY!")


def reader_and_concat_all_files_in_directory_to_one_file(path,concat_into_files_in_bytes):
#parse all path   
    for link in os.listdir(path):
         if os.path.isdir(f"{path}/{link}"):
              reader_and_concat_all_files_in_directory_to_one_file(f"{path}/{link}",concat_into_files_in_bytes)
         else:
            concat_into_files_in_bytes += read_file(f"{path}/{link}") 


def read_file(path):
      file = open(f"{path}","rb")
      get_into = file.read()
      file.close()
      return get_into


def get_hash_sum(method,get_into,out_file):
#method = hashlib.new(f"{method}") - see function get_method
      method.update(get_into)
      out_result( method.hexdigest(), out_file )


def out_result(hash_sum,out_file):
   if out_file:
      out_hash_in_file(hash_sum)
   else:   
      print(hash_sum)


def out_hash_in_file(hash_sum):
   out_file = open("hash.txt", "a+")
   out_file.write(hash_sum + "\n")
   print("The program is complete. The result of the spent program can be found in a hash.txt")


def main():
   get_info_about_out_result()


if __name__ == '__main__':
   main()
